package mouse;

import impsoft.bots.input.MouseCommand;
import impsoft.scripting.ibot.structs.XY;
import impsoft.utils.ibot.RandomGenerator;

import java.awt.Rectangle;

import base.DreamScript;
import base.DreamUtility;

public class Mouse extends DreamUtility {
	private MouseCommand mouseCommand = null;

	public Mouse(DreamScript cs) {
		super(cs);
	}

	public boolean isMouseBusy() {
		return mouseCommand != null && !mouseCommand.isDone() && mouseCommand.isRunning();
	}

	public void kill() {
		if (mouseCommand != null) {
			mouseCommand.fullStop();
			mouseCommand = null;
		}
	}

	public void waitForMouse() throws InterruptedException {
		while (isMouseBusy()) {
			cs.sleep(10);
		}
	}

	public void clickLeft(Rectangle target) throws InterruptedException {
		move(new XY(target.x + RandomGenerator.random(target.width), target.y + RandomGenerator.random(target.height)));
		clickLeft(cs.getCurrentMouseXY());
	}

	public void clickLeft(XY xy) throws InterruptedException {
		if (isMouseBusy()) {
			mouseCommand.changeDestination(xy.x, xy.y);
		} else {
			mouseCommand = MouseCommand.ClickLeft(cs.getPriority(), Thread.currentThread(), xy.x, xy.y);
			cs.enterCommand(mouseCommand, false);
		}

		while (isMouseBusy()) {
			cs.sleep(10);
		}

		kill();
	}

	public void clickRight(Rectangle target) throws InterruptedException {
		move(new XY(target.x + RandomGenerator.random(target.width), target.y + RandomGenerator.random(target.height)));
		clickRight(cs.getCurrentMouseXY());
	}

	public void clickRight(XY xy) throws InterruptedException {
		if (isMouseBusy()) {
			mouseCommand.changeDestination(xy.x, xy.y);
		} else {
			mouseCommand = MouseCommand.ClickRight(cs.getPriority(), Thread.currentThread(), xy.x, xy.y);
			cs.enterCommand(mouseCommand, false);
		}

		while (isMouseBusy()) {
			cs.sleep(10);
		}

		kill();
	}

	public void move(Rectangle target) throws InterruptedException {
		XY xy = new XY(target.x + RandomGenerator.random(target.width), target.y
				+ RandomGenerator.random(target.height));

		if (isMouseBusy()) {
			mouseCommand.changeDestination(xy.x, xy.y);
		} else {
			mouseCommand = MouseCommand.Move(cs.getPriority(), Thread.currentThread(), xy.x, xy.y);
			cs.enterCommand(mouseCommand, false);
		}

		while (isMouseBusy()) {
			cs.sleep(10);
		}

		kill();
	}

	public void move(XY xy) throws InterruptedException {
		if (isMouseBusy()) {
			mouseCommand.changeDestination(xy.x, xy.y);
		} else {
			mouseCommand = MouseCommand.Move(cs.getPriority(), Thread.currentThread(), xy.x, xy.y);
			cs.enterCommand(mouseCommand, false);
		}

		while (isMouseBusy()) {
			cs.sleep(10);
		}

		kill();
	}
}
